extends IBasicComponent


class_name TimerTrigger
"""
使用process作为触发来源的触发器
"""


## 触发的间隔时间
@export var wait_time: float = 1: set = __set_interval
## 触发的持续时间
@export var duration: float = 0
## 每次使用is_enable启停时自动重置上次的累计时间
@export var is_auto_reset: bool = false
## 关联的ProgressBar进度条
@export var progress_bar: Range = null

@export_category("Event")
## 需要触发的事件
@export var event: IEventActuator = null
## 停止时触发的事件
@export var complete_event: IEventActuator = null
@export_category("")


## 需要修改的增量时间
var increase_value: float: set = increase


var __progress_increment: float = 100 / wait_time
var __progress_value: float = 0

var __update_tick: float = 0
var __update_duration: float = 0


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "event": IComponent.find_child.bind(self, func(x): return x is IEventActuator, event),
        "wait_time": func(): return wait_time > 0,
    }, super.__check_exports())

func __set_enable(value: bool) -> void:
    super.__set_enable(value)
    if value and is_auto_reset:
        __update_duration = 0
        __on_interval()

func __set_interval(value: float) -> void:
    if is_zero_approx(value):
        push_error("TimerTrigger.wait_time is zero")
        return
    wait_time = value
    __progress_increment = 100 / wait_time

func __update_progress() -> void:
    if progress_bar:
        progress_bar.value = max(__progress_value, 100)

func __on_interval() -> void:
    __update_tick = 0
    __progress_value = 0
    __update_progress()
    IEventActuator.safe_execute(event)

func __on_duration() -> void:
    __update_duration = 0
    IEventActuator.safe_execute(complete_event)

func _physics_process(delta: float) -> void:
    __update_tick += delta
    __progress_value += __progress_increment * delta
    __update_progress()
    if __update_tick > wait_time:
        __update_duration += __update_tick
        __on_interval()
        if duration > 0 and __update_duration > duration:
            __on_duration()
            IComponent.set_enable_process(self, false)

# 返回剩余的冷却时间
func get_left_interval() -> float:
    return clampf(wait_time - __update_tick, 0, wait_time)

# 增加当前间隔
func increase(value: float) -> void:
    __update_tick = clampf(__update_tick + value, 0, wait_time)
    __progress_value = __update_tick * __progress_increment
    __update_progress()
